package com.example.amap.ui.map

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.ui.viewinterop.AndroidView
import com.example.amap.location.bean.LocationInfo
import com.example.amap.location.observer.ILocationObserver
import com.example.amap.manager.ServiceManager
import com.example.amap.map.IMapView
import com.example.amap.ui.map.ui.navigation.AppNavigation
import com.example.amap.ui.map.ui.theme.AMapV0Theme

class MapActivity : ComponentActivity() {

    private var mapView: IMapView? = null

    private val mLocationObserver = object : ILocationObserver {
        override fun onLocationChanged(locationInfo: LocationInfo?) {
            mapView?.onLocationUpdate(
                locationInfo?.lon ?: 0.0,
                locationInfo?.lat ?: 0.0,
                locationInfo?.dir ?: 0f
            )
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        mapView = ServiceManager.getMapService()?.createMapView(this)
        mapView?.getMapView()?.let { aMap ->
            setContent {
                AMapV0Theme {
                    AndroidView({ aMap })
                    AppNavigation()
                }
            }
        }
        mapView?.showMyLocationIcon()
        ServiceManager.getLocationService()?.addLocationObserver(mLocationObserver)
    }

    override fun onDestroy() {
        super.onDestroy()
        ServiceManager.getLocationService()?.removeLocationObserver(mLocationObserver)
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        mapView?.onSaveInstanceState(outState)
    }
}
